#include"Queue.h"

//初始化
void QueueInit(Queue* pq)
{
	assert(pq);
	pq->phead = NULL;
	pq->ptail = NULL;
	pq->size = 0;
}
//销毁队列
void QueueDeatroy(Queue* pq)
{
	assert(pq);
	QNode* cur = pq->phead;
	while (cur)
	{
		QNode* next = cur->next;
		free(cur);
		cur = next;
	}
	pq->phead = NULL;
	pq->ptail = NULL;
	pq->size = 0;
	
}
//队尾入列
void QueuePush(Queue* pq, QDataType x)
{
	assert(pq);
	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	newnode->next = NULL;
	newnode->val = x;
	if (pq->ptail == NULL)
	{
		pq->phead = pq->ptail = newnode;
	}
	else
	{
		//现在newnode是新的尾结点
		pq->ptail->next = newnode;
		pq->ptail = newnode;
	}
	pq->size++;
}
//队头出列
void QueuePop(Queue* pq)
{
	assert(pq);
	assert(pq->phead); 
	//保存当前节点
	QNode* tmp = pq->phead;
	//phead往下走
	pq->phead = pq->phead->next;
	free(tmp);
	tmp = NULL;
	if (pq->phead = NULL)
	{
		pq->ptail = NULL;
	}
	pq->size--;
}
//获取队列头部元素
QDataType QueueFront(Queue* pq)
{
	assert(pq);

	assert(pq->phead);
	return pq->phead->val;
}
//获取队列尾部元素
QDataType QueueBack(Queue* pq)
{
	assert(pq);
	assert(pq->phead);
	return pq->ptail;
}
//检测队列是否为空，如果为空返回非零结果，如果非空返回0 
bool QueueEmpty(Queue* pq)
{
	assert(pq);
	return pq->phead == NULL;
}
//获取队列中有效元素个数
int QueueSize(Queue* pq)
{
	assert(pq);
	return pq->size;
}
